package com.cke.yang.security.domain.repository.impl;

import com.cke.yang.security.domain.entity.SecRole;
import com.cke.yang.security.domain.entity.SecUserRelationRole;
import com.cke.yang.security.domain.repository.SecRoleRepository;
import com.cke.yang.security.infra.mapper.SecRoleMapper;
import com.cke.yang.security.infra.mapper.SecUserRelationRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色Repository实现类
 *
 * @author yuyang
 */
@Slf4j
@Repository
public class SecRoleRepositoryImpl implements SecRoleRepository {

    @Resource
    private SecRoleMapper secRoleMapper;

    @Resource
    private SecUserRelationRoleMapper secUserRelationRoleMapper;

    @Override
    public List<SecRole> getRoleListByUserId(Long userId) {
        log.debug("根据用户ID获取角色列表, userId: {}", userId);

        if (userId == null) {
            log.warn("用户ID为空，返回空列表");
            return List.of();
        }

        // 1. 根据用户ID查询用户角色关联关系
        LambdaQueryWrapper<SecUserRelationRole> relationQueryWrapper = new LambdaQueryWrapper<>();
        relationQueryWrapper.eq(SecUserRelationRole::getUserId, userId);
        List<SecUserRelationRole> userRoleRelations = secUserRelationRoleMapper.selectList(relationQueryWrapper);

        if (userRoleRelations.isEmpty()) {
            log.debug("用户ID: {} 没有关联任何角色", userId);
            return List.of();
        }

        // 2. 提取角色ID列表
        List<Long> roleIds = userRoleRelations.stream()
                .map(SecUserRelationRole::getRoleId)
                .collect(Collectors.toList());

        // 3. 根据角色ID列表查询角色信息
        LambdaQueryWrapper<SecRole> roleQueryWrapper = new LambdaQueryWrapper<>();
        roleQueryWrapper.in(SecRole::getRoleId, roleIds);
        List<SecRole> roles = secRoleMapper.selectList(roleQueryWrapper);

        log.debug("用户ID: {} 关联的角色数量: {}", userId, roles.size());
        return roles;
    }

    @Override
    public List<SecRole> getAllRoles() {
        log.debug("获取所有角色列表");
        // 查询所有角色
        List<SecRole> roles = secRoleMapper.selectList(null);
        log.debug("系统中角色总数量: {}", roles.size());
        return roles;
    }

}

